package com.srwl.mytx.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ContactMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "NotifyMessageAdapter";
    private Context context;
    private List<Message> messageList;
    private NotifyMessageInteractionListener listener;


    public ContactMessageAdapter(Context context, List<Message> messageList, NotifyMessageInteractionListener listener) {
        this.context = context;
        this.messageList = messageList;
        this.listener = listener;
    }

    @Override
    public int getItemViewType(int position) {
        return messageList.get(position).getSubType();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.notify_message_contact_item_layout, parent, false);
        return new ContactViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        final Message notify = messageList.get(position);
        ContactViewHolder contactViewHolder = (ContactViewHolder) holder;

        if (notify.getTitle() != null) {
            contactViewHolder.tv_nick.setText(notify.getTitle());
        }
        if (notify.getIcon() != null) {
           //Glide.with(context).load(notify.getIcon()).diskCacheStrategy(DiskCacheStrategy.ALL).into(contactViewHolder.iv_avatar);
            GlideLoadUtils.glideLoad(context,notify.getIcon(),contactViewHolder.iv_avatar);
        }
        if (notify.getContent() != null) {
            contactViewHolder.tv_message.setText(notify.getContent());
        }
        if (notify.getCreated() != null) {
            contactViewHolder.tv_date.setText(DateUtils.getTimestampString(notify.getCreated()));
        }
        if (notify.getSubType() == Constant.PUSH_MESSAGE_REQUEST_ADD_CONTACT) {//如果消息类型是 请求添加好友的，那么根据 3种不同的消息状态：已读、已同意、已拒绝，来决定显示或者隐藏同意、拒绝按键
            handleAddContactMessage(notify, contactViewHolder);
        } else {
            contactViewHolder.btn_agree.setVisibility(View.GONE);
            contactViewHolder.btn_refuse.setVisibility(View.GONE);
            contactViewHolder.ll_authority.setVisibility(View.GONE);
            if (notify.getSubType() == Constant.PUSH_MESSAGE_ACCEPT_ADD_CONTACT) {
                contactViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        User contactUserInfo = Helper.getInstance().getContactUserInfo(notify.getFromId());
                        if (contactUserInfo != null) {
                            context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, contactUserInfo));
                        }
                    }
                });
            }
        }


        contactViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (listener != null) {
                    listener.onItemLongClick(notify);
                }
                return false;
            }
        });

    }

    private void handleAddContactMessage(Message notify, ContactViewHolder contactViewHolder) {
        if (notify.getReadState() == Constant.NOTIFY_MESSAGE_STATUS_READED) {
            if (notify.getState() == Constant.INVITE_MESSAGE_STATUS_AGREED) {
                contactViewHolder.btn_agree.setVisibility(View.VISIBLE);
                contactViewHolder.btn_agree.setEnabled(false);
                contactViewHolder.btn_agree.setText("已同意");
                contactViewHolder.btn_agree.setBackgroundResource(R.drawable.tx_btn_shape_gray);
                contactViewHolder.btn_refuse.setVisibility(View.GONE);
                contactViewHolder.ll_authority.setVisibility(View.GONE);
                contactViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        User contactUserInfo = Helper.getInstance().getContactUserInfo(notify.getFromId());
                        context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, contactUserInfo));
                    }
                });
            } else if (notify.getState() == Constant.INVITE_MESSAGE_STATUS_REFUSED) {
                contactViewHolder.btn_agree.setVisibility(View.GONE);
                contactViewHolder.btn_refuse.setVisibility(View.VISIBLE);
                contactViewHolder.btn_refuse.setEnabled(false);
                contactViewHolder.btn_refuse.setText("已拒绝");
                contactViewHolder.btn_refuse.setBackgroundResource(R.drawable.tx_btn_shape_gray);
                contactViewHolder.ll_authority.setVisibility(View.GONE);
            } else {
                contactViewHolder.btn_agree.setVisibility(View.VISIBLE);
                contactViewHolder.btn_agree.setBackgroundResource(R.drawable.tx_btn_shape_white);
                contactViewHolder.btn_agree.setEnabled(true);
                contactViewHolder.btn_refuse.setVisibility(View.VISIBLE);
                contactViewHolder.btn_refuse.setBackgroundResource(R.drawable.tx_btn_shape_white);
                contactViewHolder.btn_refuse.setEnabled(true);
                contactViewHolder.ll_authority.setVisibility(View.VISIBLE);
                contactViewHolder.btn_agree.setOnClickListener(v -> agree(contactViewHolder, notify));

                contactViewHolder.btn_refuse.setOnClickListener(v -> refuse(contactViewHolder, notify));
            }
        }
    }


    @Override
    public int getItemCount() {
        return messageList.size();
    }

    private void refuse(final ContactViewHolder holder, final Message notify) {

        // 弹出拒绝提醒
        ConfirmDialog dialog = new ConfirmDialog(context, "提醒", "拒绝后对方在5天内无法再向你发送好友请求", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                refuseInvitation(holder, notify);

            }
        });
        dialog.show();

    }

    /**
     * 拒绝添加联系人
     *
     * @param holder
     * @param message
     */
    private void refuseInvitation(final ContactViewHolder holder, final Message message) {
        final Contact contact = new Contact();
        contact.settId(message.getFromId());
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        body.put("ct", contact);
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .refuseAddContact(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            toast(holder.btn_refuse, context.getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:

                                    toast(holder.btn_refuse, context.getString(R.string.login_expire));
                                    return;
                            }
                        }
                        toast(holder.btn_refuse, context.getString(R.string.refuse_invite));

                        updateMsg(message, Constant.INVITE_MESSAGE_STATUS_REFUSED);
                        notifyDataSetChanged();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        toast(holder.btn_refuse, context.getString(R.string.system_busy));
                    }
                });
    }

    private void agree(final ContactViewHolder holder, final Message message) {
        //这种情况 ，出现可能很小吧
        if (Helper.getInstance().isNormalContact(message.getFromId())) {
            updateMsg(message, Constant.INVITE_MESSAGE_STATUS_AGREED);
            notifyDataSetChanged();
            toast(holder.btn_agree, "对方已经是你的的好友");
            return;
        }

        Contact contact = new Contact();

        if (holder.cb_location.isChecked()) {
            contact.setTLocation("1");
        } else {
            contact.setTLocation("0");
        }

        addContactToService(holder, contact, message);

    }

    /**
     * 向服务端添加联系人
     *
     * @param updateContact
     * @param msg
     */
    private void addContactToService(final ContactViewHolder viewHolder, final Contact updateContact, final Message msg) {
        final ProgressDialog pd = new ProgressDialog(context);
        pd.setMessage("正在保存联系人信息");
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        updateContact.settId(msg.getFromId());
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        body.put("ct", updateContact);
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .addContact(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        pd.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            toast(viewHolder.btn_agree, context.getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            toast(viewHolder.btn_agree, context.getString(R.string.add_contact_faile));
                            return;
                        }
                        //服务端没有返回对方的用户数据，从notify中只有用户的 id nick avatar ,如果有必须获取更多数据，可以在请求添加好友的时候，在notify中携带更多用户信息，或者在此同意添加好友的请求中，返回对方用户数据
                        User targetUser = new User(msg.getFromId());
                        targetUser.setUsername(msg.getTitle());//以前是用nick 字段显示用户名字，现在换成username字段，服务端传回的就是用户名，
                        targetUser.setAvatar(msg.getIcon());
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(targetUser);

                        //获取从服务端返回的完整的Contact 数据，保存在本地数据库
                        JSONObject jsonObject = (JSONObject) result.getData();
                        //
                        Contact contact = jsonObject.toJavaObject(Contact.class);

//                        contact.setmId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                        //我作为被添加好友的一方，在数据库中，我的用户id，是在t_id的位置，但是在前端，联系人表和用户表是两个关联的表，外键就是tid,所以在这里需要把tid 设置为对方用户的id
                        contact.settId(contact.getUser().getuId());
                        DBManager.getInstance().getDaoSession().getContactDao().insertOrReplace(contact);
                        Helper.getInstance().refreshCache();
                        updateMsg(msg, Constant.INVITE_MESSAGE_STATUS_AGREED);
                        notifyDataSetChanged();
                        toast(viewHolder.btn_agree, context.getString(R.string.add_contact_success));
                        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context);
                        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANGED));

                        //构造一条信息，显示到会话页面，显示添加联系人完成，
                        Message message = new Message();
                        message.setId(IDUtils.genOrderItemId());
                        message.setFromId(targetUser.getuId());
                        message.setToId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                        message.setVisible(Constant.MESSAGE_VISIBLE);
                        message.setType(Constant.C2C_MESSAGE);
                        message.setSubType(Constant.IM_TYPE_TEXT);
                        message.setContent("添加联系人完成");
                        message.setCreated(new Date());
                        IMSClientBootstrap.getInstance().sendLocalMessage(message);


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        pd.dismiss();
                        toast(viewHolder.btn_agree, context.getString(R.string.system_busy));
                    }
                });
    }


    private void updateMsg(Message msg, int inviteMessageStatus) {
        msg.setState(inviteMessageStatus);
        // msg.update();
        DBManager.getInstance().getDaoSession().getMessageDao().update(msg);


    }

    private void toast(final View view, final String message) {
        ((Activity) context).runOnUiThread(new Runnable() {

            @Override
            public void run() {

                Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
            }
        });
    }


    protected class ContactViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_avatar)
        ImageView iv_avatar;
        @BindView(R.id.tv_nick)
        TextView tv_nick;
        @BindView(R.id.tv_message)
        TextView tv_message;
        @BindView(R.id.btn_agree)
        Button btn_agree;
        @BindView(R.id.btn_refuse)
        Button btn_refuse;
        @BindView(R.id.tv_date)
        TextView tv_date;
        @BindView(R.id.ll_authority)
        LinearLayout ll_authority;
        @BindView(R.id.cb_location)
        CheckBox cb_location;

        public ContactViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


}
